<?php

class DBConfig
{
    // mysql 主机列表, 读,写分别配置
    // DBmysql::getConnect() 会随机查找可用host, 直到找到可用的 
    // utf8mb4: 支持emoji表情的字符集, 最新版的mysql已设为默认字符集
    public static $hosts = array(
        'default' => array(
            'write' => array(
                array('host' => '127.0.0.1', 'username' => '', 'password' => '', 'port' => 3306, 'charset' => 'utf8'),
                // 其他可用主机
            ),
            'read' => array(
                array('host' => '127.0.0.1', 'username' => '', 'password' => '', 'port' => 3306, 'charset' => 'utf8'),
                array('host' => '127.0.0.2', 'username' => '', 'password' => '', 'port' => 3306, 'charset' => 'utf8'),
                // 其他可用主机
            )
        ),

        'other' => array(
            'write' => array(),
            'read' => array()
        )
    );
    
    //table info
    //虚拟表名 => 虚拟主机名, 数据库名, 表名
    //将所有表在此备案, 方便管理, 其中虚拟主机名对应self::$hosts 键名, 如 default
    public static $TableInfo = array(
        'user'             => 'default, test, user',
        'role'             => 'default, test, role',
        'role_bind'        => 'default, test, role_bind',
        'test_(\d+)_(\d+)' => 'default, test, test_$1_$2',
        'article' => 'default, test, article',
        'article_cats' => 'default, test, article_cats',
    );
    
    /**
     * @param string $modelName 对应$TableInfo的键名
     * @return array
     * @throws Exception
     */
    public static function getDBInfo($modelName)
    {
        $strDT = '';
        if (array_key_exists($modelName, self::$TableInfo)) {
            $strDT = self::$TableInfo[$modelName];//获得database table 字符串
        } else {
            foreach (self::$TableInfo as $pattern => $dt) {
                if (strpos($pattern, '(') !== FALSE) {
                    preg_match('#' . $pattern . '#', $modelName, $matches);
                    
                    if (!empty($matches)) {
                        $strDT = $dt;
                        foreach ($matches as $key => $value) {
                            $strDT = str_replace('$' . $key, $value, $strDT);
                        }
                        break;
                    }
                }
            }
        }
        
        if (!empty($strDT)) {
            $strDT = preg_replace('#,\s+#', ',', $strDT);//去掉空白
            $arr   = explode(',', $strDT);
            return array(
                'vhost' => $arr[0],
                'database' => $arr[1],
                'table' => $arr[2],
            );
        } else {
            self::error("未找到数据表 {$modelName} !");
        }
    }
    
    public static function error($msg)
    {
        throw new Exception($msg);
    }
}